package com.hc.testaudio.deletea.test1.ui

import android.media.MediaPlayer
import android.media.audiofx.Visualizer
import android.os.Bundle
import android.widget.Toast
import com.hc.testaudio.R
import com.hc.testaudio.deletea.test1.DataPoolUtil
import com.hc.testaudio.deletea.test1.IMediaListener
import com.hc.testaudio.deletea.test1.MediaUtil
import com.hc.testaudio.deletea.test1.VisualizerUtil
import com.hc.testaudio.deletea.ui.BaseActivity
import com.hc.testaudio.deletea.test1.chart.BarChartUtil
import com.hc.testaudio.deletea.test1.chart.LineChartUtil
import com.yc.yclibx.comment.YcLog
import kotlinx.android.synthetic.main.bar_chart_activity.*
import kotlin.collections.ArrayList
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.log10


/**
 *
 */
class BarChartActivityOle : BaseActivity() {
    val Hz = listOf(8000, 11025, 22050, 32000, 44100, 47250, 48000, 50000, 50400, 96000, 192000, 282240000)
    var mMediaUtil = MediaUtil()
    var mVisualizerUtil = VisualizerUtil()
    lateinit var mBarChartUtil: BarChartUtil
    lateinit var mBarChartUtil2: BarChartUtil
    lateinit var mLineChartUtil: LineChartUtil
    private val mDataPool = DataPoolUtil()
    override fun getLayoutId(): Int {
        return R.layout.bar_chart_activity
    }

    override fun initView(savedInstanceState: Bundle?) {
        //        mDataPool.setGetDataCall { byteData, samplingRate, captureSize ->
        //            val fftData = FftUtil.getFFt(byteData)
        //            show(fftData, samplingRate, captureSize, mBarChartUtil2)
        //        }
        mBarChartUtil = BarChartUtil(barChart, activity)
        mBarChartUtil2 = BarChartUtil(barChart2, activity)
        mLineChartUtil = LineChartUtil(lineChart, activity)

        mMediaUtil.mMediaListener = object : IMediaListener {
            override fun onStartPlayingListener(mp: MediaPlayer) {
                mVisualizerUtil.start(mp.audioSessionId) //开始采集播放音频的数据
            }

            override fun onCompletionListener() {
                mVisualizerUtil.stop()
            }

            override fun onErrorListener() {
                mVisualizerUtil.stop()
            }
        }

        mVisualizerUtil.mDataCaptureListener = object : Visualizer.OnDataCaptureListener {
            override fun onFftDataCapture(visualizer: Visualizer?, fft: ByteArray?, samplingRate: Int) {
                //                YcLog.e("fft数量：" + fft!!.size)
                var max = 0f
                //频域数据
                if (fft == null) {
                    Toast.makeText(activity, "频域数据为空", Toast.LENGTH_SHORT)
                        .show()
                } else {
                    show(fft, samplingRate, visualizer!!.captureSize, mBarChartUtil)
                }
            }

            override fun onWaveFormDataCapture(visualizer: Visualizer?, waveform: ByteArray, samplingRate: Int) {
                val newData = ByteArray(waveform.size)
                for (i in waveform.indices) {
                    newData[i] = (when {
                        waveform[i].toInt() == 0 -> 0
                        waveform[i] > 0 -> 128 - waveform[i]
                        else -> (waveform[i] + 128) * -1
                    }).toByte()
                }

//                val fftData = FftUtil.getFFt(newData)
//                show(fftData, samplingRate, samplingRate, mBarChartUtil2)
                //                mDataPool.captureSize = samplingRate
                //                mDataPool.samplingRate = visualizer!!.captureSize
                //                mDataPool.add(waveform)
                //                YcLog.e("waveform数量：" + waveform!!.size)
                // 时域数据
                //                put(waveform)
                //                val standard = 12.283f //设置电压的基准值
                val standard = 10f //设置电压的基准值
                if (waveform != null) {
                    val dataY = ArrayList<Float>()
                    val dataX = ArrayList<Float>()
                    YcLog.e("samplingRate：" + samplingRate)
                    val time = 1000 / (samplingRate.toDouble() / 1000)
                    var max = 0f
                    for (i in waveform.indices) {
                        val y: Float = (when {
                            waveform[i].toInt() == 0 -> 0f
                            waveform[i] > 0 -> (128f - waveform[i]) * standard / 128f
                            else -> (waveform[i] + 128f) * standard / 128f * -1
                        }).toFloat()
                        if (y > max) {
                            max = y
                        }
                        dataY.add(y)
                        dataX.add((i * time).toFloat())
                    }
                    YcLog.e("时域" + max)
                    mLineChartUtil.add(dataX, dataY)
                    mLineChartUtil.invalidate()
                } else {
                    Toast.makeText(activity, "时域数据为空", Toast.LENGTH_SHORT)
                        .show()
                    return
                }

            }
        }
        chartStartBtn.setOnClickListener {
            mMediaUtil.play() //开始播放音频
        }
        //        chartStartBtn2.setOnClickListener {
        //            try {
        //                val minBufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncodeing)
        //                val audioRecord = AudioRecord(MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncodeing, minBufferSize)
        //                mAudioHelper.baseLine = audioSv.height - 100f
        //                mAudioHelper.frequence = frequency
        //                mAudioHelper.start(audioRecord, minBufferSize, audioSv)
        //                Toast.makeText(activity, "当前设备支持您所选择的采样率:$frequency", Toast.LENGTH_SHORT)
        //                    .show()
        //            } catch (e: Exception) {
        //                Toast.makeText(activity, "当前设备不支持你所选择的采样率:$frequency,请重新选择", Toast.LENGTH_SHORT)
        //                    .show()
        //            }
        //        }
    }

    fun show(fftData: ByteArray, samplingRate: Int, captureSize: Int, barChartUtil: BarChartUtil) {
        val tempLength = fftData.size / 2
        val frequencyCounts = tempLength + 1 //有效的fft数据 1+1+(fftData.size/2)（即有效的采样数）
        var magnitudes = FloatArray(frequencyCounts) //振幅
        var phases = FloatArray(frequencyCounts) //相位
        //fft数据里 第0个 和 第fft.size/2个 数据特殊只有实部
        magnitudes[0] = abs(fftData[0].toInt()).toFloat()      // 直流
        magnitudes[tempLength] = abs(fftData[tempLength].toInt()).toFloat()   // 实数
        phases[0] = 0f
        phases[tempLength] = 0f
        for (k in 1 until tempLength) {
            val i = k * 2
            magnitudes[k] = hypot(fftData[i].toDouble(), fftData[i + 1].toDouble()).toFloat()
            phases[k] = atan2(fftData[i + 1].toDouble(), fftData[i].toDouble()).toFloat()
            if (magnitudes[k] > 0) {
                magnitudes[k] = 20 * log10(magnitudes[k])
            }
            //            if (magnitudes[k] > max) {
            //                max = magnitudes[k]
            //            }
        }
        val frequency = FloatArray(frequencyCounts) //频率
        val frequencyEach = samplingRate / 1000f / 1000 / captureSize  //频率间隔
        for (i in 0 until tempLength + 1) {
            frequency[i] = i * frequencyEach
        }
        barChartUtil.add(frequency.toList(), magnitudes.toList())
        barChartUtil.invalidate()
    }

    fun show(fftData: DoubleArray, samplingRate: Int, captureSize: Int, barChartUtil: BarChartUtil) {
        //   直流      实部 虚部      频率范围 0-采样率/2 getSamplingRate()
        //    0    1    2    3    4    5       n-2       n-1        n=getCaptureSize()
        //    R0  Rn/2 R1   L1    R2   L2    R(n-1)/2  L(n-1)/2
        //   k次频率 = getSamplingRate() * k / (n/2)
        val tempLength = fftData.size / 2
        val frequencyCounts = tempLength + 1 //有效的fft数据 1+1+(fftData.size/2)（即有效的采样数）
        var magnitudes = FloatArray(frequencyCounts) //振幅
        var phases = FloatArray(frequencyCounts) //相位
        //fft数据里 第0个 和 第fft.size/2个 数据特殊只有实部
        magnitudes[0] = abs(fftData[0].toInt()).toFloat()      // 直流
        magnitudes[tempLength] = abs(fftData[tempLength].toInt()).toFloat()   // 实数
        phases[0] = 0f
        phases[tempLength] = 0f
        for (k in 1 until tempLength) {
            val i = k * 2
            magnitudes[k] = hypot(fftData[i].toDouble(), fftData[i + 1].toDouble()).toFloat()
            phases[k] = atan2(fftData[i + 1].toDouble(), fftData[i].toDouble()).toFloat()
            if (magnitudes[k] > 0) {
                magnitudes[k] = 20 * log10(magnitudes[k])
            }
            //            if (magnitudes[k] > max) {
            //                max = magnitudes[k]
            //            }
        }
        val frequency = FloatArray(frequencyCounts) //频率
        val frequencyEach = samplingRate / 1000f / 1000 / captureSize  //频率间隔
        for (i in 0 until tempLength + 1) {
            frequency[i] = i * frequencyEach
        }
        barChartUtil.add(frequency.toList(), magnitudes.toList())
        barChartUtil.invalidate()
    }

    override fun onDestroy() {
        super.onDestroy()
        mVisualizerUtil.stop()
    }
    //
    //    var frequency = 44100 //通用采样率
    //    val channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO
    //    val audioEncodeing = AudioFormat.ENCODING_PCM_16BIT
    //    var mAudioHelper = AudioHelper()
}